package cn.felord.debezium.config;


/**
 * 主从库
 */
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 添加此配置，否则 报`The dependencies of some of the beans in the application context form a cycle`
 */
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
@Configuration
@PropertySource("classpath:application.yml")
@MapperScan(basePackages = "com.hs.reader3.dao.mapper")
public class DynamicDataSourceConfig {

    @Bean("master1")
    @ConfigurationProperties(prefix = "spring.datasource.master1")
    public DataSource master1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean("master2")
    @ConfigurationProperties(prefix = "spring.datasource.master2")
    public DataSource master2DataSource() {
        return DataSourceBuilder.create().build();
    }

    //设置动态数据源为主数据源
    @Bean
    @Primary
    public DataSource dynamicDataSource() {
        Map<Object, Object> dataSourceMap = new HashMap<>(2);
        dataSourceMap.put("master1", master1DataSource());
        dataSourceMap.put("master2", master2DataSource());
        //设置动态数据源
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.setDefaultTargetDataSource(master1DataSource());
        return dynamicDataSource;
    }
}
